<template>
	<view class="page">
		<button open-type="chooseAvatar" class="up-reset-button" @chooseavatar="handelChooseavatar" style="display: block;">
			<up-image :src="avatarUrl" shape="circle" class="avatar" width="200rpx" height="200rpx"></up-image>
		</button>
		<up-cell-group :border="false">
			<up-cell  title="用户昵称">
				<template #right-icon>
					<up-input
						v-model="userInfo.nickName"
					    placeholder="请输入"
					    border="none"
						inputAlign="right"
						:customStyle="{'width': '300rpx'}"
					></up-input>
				</template>
			</up-cell>
		</up-cell-group>
		<view class="btn-box">
			<up-button type="primary" shape="circle" color="#D19973" text="提交" @click="updateUserInfo"></up-button>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, computed } from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app'
	
	const userInfo = reactive({
		nickName: null,
		avatar: null
	})
	const storageData = reactive({
		token: null,
		user: {}
	})
	
	onShow(() => {
		storageData.token = uni.getStorageSync('token')
		storageData.user = uni.getStorageSync('user')
		userInfo.avatar = storageData.user.avatar
		userInfo.nickName = storageData.user.nickName
	})
	
	const avatarUrl = computed(() => {
		return userInfo.avatar && userInfo.avatar != '' ? userInfo.avatar : 'https://gamumu.hilumo.com/prod-api/files/down/1950496566954209280.png'
	})
	
	function handelChooseavatar(detail) {
		const name = new Date().getTime()
		const arr = `${detail.detail.avatarUrl}`.split('.')
		const ext = `.${arr[arr.length - 1]}`
		uni.uploadFile({
			url: `${getApp().globalData.baseUrl}/prod-api/files/tencentoss/upload`,
			filePath: detail.detail.avatarUrl,
			header: {
				'Authorization': "Bearer " + storageData.token,
			},
			name: 'file',
			formData: {
				name,
				ext,
				type: 0
			},
			success: (res) => {
				const data = JSON.parse(res.data)
				if (data.code === 200) {
					userInfo.avatar = data.file.url
				} else {
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					})
				}
			},
			fail: () => {
				uni.showToast({
					icon: 'none',
					title: '上传失败'
				})
			}
		});
	}
	
	function updateUserInfo() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/wechat/update/mineInfo`,
			method: 'POST',
			header: {
				'Authorization': "Bearer " + storageData.token,
			},
			data: {
				avatar: userInfo.avatar,
				nickName: userInfo.nickName
			},
			success: (res) => {
				if (res.data.code === 200) {
					uni.setStorageSync('user', res.data.data)
					uni.switchTab({
						url: '/pages/my/my'
					})
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}
</script>

<style lang="scss" scoped>
	.page {
		padding: 0 40rpx;
		box-sizing: border-box;
	}
	.avatar {
		display: block;
		margin: 120rpx auto;
	}
	
	.btn-box {
		margin: 150rpx auto;
	}
</style>